class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['PageIndex01'] = 1;
        item['Limit01'] = parseInt($("#page-size_01").val());
        item['PageIndex02'] = 1;
        item['Limit02'] = parseInt($("#page-size_02").val());

        return item;
    }
    // 得到发货单主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billNo'] = $.trim($("#BillNo").val());                                 // 发货单号（自动生成）
        item['doHeaderId'] = $.trim($("#DoHeaderId").val());                         // 发货发令单标识
        item['styleNo'] = $.trim($("#StyleNo").val());                               //  
        item['garmentFactoryId'] = $.trim($("#GarmentFactoryId").val());             //   
        item['dateOfDelivery'] = $.trim($("#DateOfDelivery").val());                 // 日期
        item['grossWeight'] = $.trim($("#GrossWeight").val());                       // 
        item['netWeight'] = $.trim($("#NetWeight").val());                           // 
        item['cubage'] = $.trim($("#Cubage").val());                                 // 体积
        item['inCase'] = $.trim($("#InCase").val());                                 // 箱装
        item['description'] = formatNullInputValue($.trim($("#Description").val())); // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#BillNo").val(item.billNo);
        $("#DateOfDelivery").val(item.dateOfDelivery);
        $("#DoHeaderId").val(item.doHeaderId);
        $("#StyleNo").empty();
        if (item.styleNo !== null && (item.styleNo).indexOf("/") !== -1) {
            $("#StyleNo").append('<option value="">' + item.styleNo + '</option>');
        } else {
            $("#StyleNo").append('<option value="' + item.styleNo + '">' + item.styleNo + '</option>');
        }
        $("#DoBillNo").val(item.doBillNo);
        $("#SoNo").val(item.soNo);
        $("#CustomerName").val(item.customerName);
        $("#GarmentFactoryId").val(item.garmentFactoryId);
        $("#GarmentFactoryName").val(item.garmentFactoryName);
        $("#Destination").val(item.destination);
        $("#ShippingTypeName").val(item.shippingTypeName);
        $("#DutyManName").val(item.dutyManName);
        $("#NoOfContract").val(item.noOfContract);
        $("#GrossWeight").val(item.grossWeight);
        $("#NetWeight").val(item.netWeight);
        $("#Cubage").val(item.cubage);
        $("#InCase").val(item.inCase);
        $("#Description").val(item.description);
        $("#UpdatedBy").val(item.updatedBy);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(item.updatedDate);
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置用于控制的用户ID
        this.privateUserId = item.updatedBy;

        // 显示明细数据
        _InstancePageLinesDo.BuildDataTable(data.LinesDoList);
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
            _InstancePageLinesDo.AutoAdjustTableHeightForLines();
        });
        $("#BillNo").focus();
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    $("#Action").val(2);
                    $self.dataId = data;
                    $self.pageStatus = 2;
                    $("#menu_02").show();
                    $("#menu_03").show();
                }
            }
        });
    }
    New() {
        super.New();
        this.FetchNewBillNo();
        $("#StyleNo").empty();
        $("#tabData21 tbody").empty();
        $("#tabData31 tbody").empty();
        $("#ButSaveLines").show();
        $("#menu_02").hide();
        $("#menu_03").hide();
        $("#BillNo").focus();
    }
    FetchNewBillNo() {
        super.DoAjax(null, "/trade/shipping_order/header/fetchNewBillNo.html", function (data, $self) {
            $("#BillNo").val(data.BillNo);
        });
    }
    DoChoiceDo() {
        let _choice = new CommonChoice();
        _choice.DoChoiceDo(0, '选择发货发令单', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#DoBillNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }

                $("#DoHeaderId").val(data[0]);
                $("#DoBillNo").val(data[1]);
                $("#CustomerName").val(data[2]);
                $("#DateOfDelivery").val(data[3]);
                $("#Destination").val(data[4]);
                $("#ShippingTypeName").val(data[5]);
                $("#DutyManName").val(data[6]);
                // 设置款号
                super.DoAjax(parseInt($("#DoHeaderId").val()), "/trade/delivery_command_sheet/header/fetchStyleNoByHeaderKey.html", function (data, $self) {
                    if (data !== null && data.length !== 0) {
                        $("#StyleNo").empty();
                        let options = [];
                        options.push('<option value="-1">-- 请选择 --</option>');
                        options.push('<option value="">全部款号</option>');
                        for (let i = 0; i < data.length; i++) {
                            options.push('<option value="', data[i], '">', data[i], '</option>');
                        }
                        $("#StyleNo").html(options.join(''));
                    } else {
                        ShowErrorMessagePanel('该发货发令单没有款号信息。');
                    }
                });
            }
        });
    }
    DoChoiceGarmentFactory() {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceSupplier(params, '选择加工厂', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#GarmentFactoryName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#GarmentFactoryId").val(data[0]);
                $("#GarmentFactoryName").val(data[1]);
                $("#GarmentFactoryName").focus();
            }
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + "?id=" + $("#HeaderId").val());
    }
}

class MyPageLinesDo extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.selectedItemList = [];
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_01").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_01").val());           // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_01").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        return JSON.stringify(item);
    }
    // 取得引入的调达表明细分页信息
    FetchForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/trade/shipping_order/lines_do/fetchForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_01 i").addClass("fa-spin");
                $("#loading__indicator_01").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_01 i").removeClass("fa-spin");
            $("#loading__indicator_01").hide();
        });
    }
    BuildDataTable(result) {
        $("#tabData21 tbody").empty();
        if (result.Success === false) {
            this.rows = 0;
            this.AutoAdjustTableHeightForLines();
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_01").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_01").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_01").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_01").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_01").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_01").data("swPagination").setPage(1);
        }
        let currentPage = result.PageIndex;
        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            this.rows = 0;
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content = '';
        this.rows = result.length;        // 设置表格记录数
        this.numCheckbox = result.length;  // 设置表格记录数
        for (let i = 0; i < result.length; i++) {
            let sequence = i + 1 + (currentPage - 1) * parseInt($("#page-size_01").val());
            content += '<tr _mash_id="' + result[i].linesId + '" _mash_do_headerid="' + result[i].doHeaderId + '" _mash_do_linesid="' + result[i].doLinesId + '">';
            content += '<td><label style="margin-left:3px;" class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row" type="checkbox" onclick="_InstancePageLinesDo.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
            content += '<td style="text-align:center;">' + sequence + '</td>';
            //if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
            //    content += '<td></td>';
            //} else {
            content += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLinesDo.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            //}
            content += '<td>' + formatNullData(result[i].destination) + '</td>';
            content += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content += '<td>' + formatNullData(result[i].productName) + '</td>';
            content += '<td>' + formatNullData(result[i].colourName) + '</td>';
            content += '<td style="text-align:center;">' + formatNullData(result[i].sizeName) + '</td>';
            content += '<td>' + formatNullData(result[i].quantity) + '</td>';
            content += '<td class="edited-cell">' + formatNullData(result[i].inCase) + '</td>';
            content += '<td class="edited-cell">' + formatNullData(result[i].cartonNo) + '</td>';
            content += '<td>' + formatNullData(result[i].shippingMarkNo) + '</td>';
            content += '</tr>';
            $('#tabData21 tbody').append(content);
            content = '';
        }
        setOneTableRowColor("tabData21");
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let id = "_cell__field";
        let name = "__cell__field";
        $('#tabData21 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        this.ResetSelectRowStatus();
    }
    ImportDeliveryCommandSheet($obj) {
        let _choice = new CommonChoice();
        _choice.DoChoiceDoLines(1, $("#DoHeaderId").val(), $("#StyleNo").val(), '选择发令单明细', (data) => {
            if (data) {
                let _doLinesIdList = [];
                for (let i = 0; i < data.length; i++) {
                    _doLinesIdList.push(data[i].doLinesId);
                }
                //for (let key in data.SelectedLinesList) {
                //    _doLinesIdList.push(key);
                //}
                let params = {};
                params['HeaderId'] = parseInt($("#HeaderId").val());
                params['InCase'] = parseInt($("#InCase").val());
                params['UserId'] = parseInt($.trim($("#UserId").val()));
                params['DoHeaderId'] = parseInt($("#DoHeaderId").val());
                params['StyleNo'] = $.trim($("#StyleNo").val());
                params['ItemList'] = _doLinesIdList;
                params['Limit01'] = parseInt($("#page-size_01").val());
                params['PageIndex01'] = parseInt($("#page_indicator_block_01").attr("_msh_page"));
                params['Limit02'] = parseInt($("#page-size_02").val());
                params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
                //params['SelectAllFlag'] = parseInt(data.SelectAllFlag);
                params['SelectAllFlag'] = parseInt(0);   // 暂时用0代替

                super.DoAjax(params, "/trade/shipping_order/lines_do/insert.html", (data, _this) => {
                    if (data.Success === true) {
                        // 刷新明细记录  
                        _this.BuildDataTable(data.LinesDoList);
                        _InstancePageLines.BuildDataTable(data.LinesList);
                        ShowSuccessMessagePanel("引入该款发货发令单成功。");
                    }
                }, $obj);
            }
        });
    }
    // 批量更新箱装
    UpdateInCase($obj) {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要更改的数据。");
            return false;
        }

        showModal(565, 275, '更改材箱装', parent.basePath + '/trade/shipping_order/lines_do/incase/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }

            // 做选择设置
            if (parent.choice_success) {
                // step 1、得到更改后的唛头号
                let _newIncase = parent.arrChoice[0][0];
                // step 2、更改唛头号
                super.DoAjax(this.GetLinesBatchData(0, _newIncase), "/trade/shipping_order/lines_do/batch_update_incase.html", function (data, _this) {
                    if (data.Success === true) {
                        // 刷新本次发货生产情况
                        _this.BuildDataTable(data.LinesDoList);
                        // 刷新合同明细
                        _InstancePageLines.BuildDataTable(data.LinesList);
                        ShowSuccessMessagePanel('更改唛头号成功。');
                        //$("#CheckAll").prop("checked", false);
                        //_this.DoCheckAll($("#CheckAll"));
                    }
                }, $obj);
            }
            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 获取本次发货生产情况数据
    GetLinesData() {
        let itemList = [];
        // 得到修改过数据
        $('#tabData21 tbody').find("tr").each(function () {
            let $tr1 = $(this);
            if ($tr1.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['billNo'] = $("#BillNo").val();
                item['linesId'] = $tr1.attr("_mash_id");
                item['doHeaderId'] = $("#DoHeaderId").val();
                item['doLinesId'] = $tr1.attr("_mash_do_linesid");
                item['inCase'] = $.trim($tr1.find('td').eq(9).text());
                item['cartonNo'] = $.trim($tr1.find('td').eq(10).text()) === "" ? null : $.trim($tr1.find('td').eq(10).text());
                item['updatedBy'] = $("#UserId").val();

                itemList.push(item);
            }
        });
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['UserId'] = parseInt($.trim($("#UserId").val()));
        params['DoHeaderId'] = parseInt($("#DoHeaderId").val());
        params['StyleNo'] = $.trim($("#StyleNo").val());
        params['ItemList'] = itemList;
        params['Limit01'] = parseInt($("#page-size_01").val());
        params['PageIndex01'] = parseInt($("#page_indicator_block_01").attr("_msh_page"));
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));

        return JSON.stringify(params);
    }
    // 得到批量处理的数据
    GetLinesBatchData(flag, value) {
        let itemList = [];
        switch (parseInt(flag)) {
            case 0: // 取得批量更新箱装
                if (Object.keys(this.selectedItemList).length > 0 && Object.keys(this.selectedItemList).length > 0) {
                    Object.keys(this.selectedItemList).forEach(function (key, index) {
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['billNo'] = $("#BillNo").val();
                        item['linesId'] = key;
                        item['doHeaderId'] = $("#DoHeaderId").val();
                        //item['doLinesId'] = $tr1.attr("_mash_do_linesid");
                        item['inCase'] = value;
                        item['updatedBy'] = $.trim($("#UserId").val());
                        itemList.push(item);
                    });
                }
                break;
            case 1:  // 取得批量删除数据
                if (Object.keys(this.selectedItemList).length > 0 && Object.keys(this.selectedItemList).length > 0) {
                    Object.keys(this.selectedItemList).forEach(function (key, index) {
                        let $tr = $(this).parent().parent().parent();
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['billNo'] = $("#BillNo").val();
                        item['linesId'] = key;
                        item['doHeaderId'] = $("#DoHeaderId").val();
                        item['updatedBy'] = $.trim($("#UserId").val());
                        item['deletedBy'] = $.trim($("#UserId").val());
                        itemList.push(item);
                    });
                }
                break;
        }

        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['UserId'] = parseInt($.trim($("#UserId").val()));
        params['DoHeaderId'] = parseInt($("#DoHeaderId").val());
        params['StyleNo'] = $.trim($("#StyleNo").val());
        params['ItemList'] = itemList;
        params['Limit01'] = parseInt($("#page-size_01").val());
        params['PageIndex01'] = parseInt($("#page_indicator_block_01").attr("_msh_page"));
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));

        return params;
    }
    SaveLines($obj) {
        //step 1、进行页面验证，失败则返回
        //let success_01 = CheckGridInput02();
        //if (!success_01)
        //    return;

        super.SaveLines("/trade/shipping_order/lines_do/update.html", function (data, _this) {
            if (data.Success === true) {
                // 刷新本次发货生产情况
                _this.BuildDataTable(data.LinesDoList);
                // 刷新合同明细
                _InstancePageLines.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("保存成功。");
            }
        }, $obj);
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['DoHeaderId'] = parseInt($("#DoHeaderId").val());
        params['InCase'] = $("#InCase").val();
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = parseInt($.trim($("#UserId").val()));
        params['Limit01'] = parseInt($("#page-size_01").val());
        params['PageIndex01'] = parseInt($("#page_indicator_block_01").attr("_msh_page"));
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        params['LinesData'] = "单据号：" + $("#BillNo").val() +
                "　款号：" + $self.parent().parent().find("td").eq(4).text() +
                "　颜色：" + $self.parent().parent().find("td").eq(6).text() +
                "　尺码：" + $self.parent().parent().find("td").eq(7).text();

        super.DeleteLines(params, "/trade/shipping_order/lines_do/delete.html", (data, _this) => {
            if (data.Success === true) {
                // 刷新本次发货生产情况
                _this.BuildDataTable(data.LinesDoList);
                // 刷新合同明细
                _InstancePageLines.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("删除成功。");
            }
        }, $self);
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        let _this = this;
        let key = $self.val();
        super.AdjustRowStatus($self, function ($row, index) {
            $('#tabData21 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置删除按钮失效
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
            let item = {};
            item['linesId'] = key;
            _this.selectedItemList[key] = item;
        }, function ($row, index) {
            $('#tabData21 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLinesDo.DeleteLines($(this))';
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete _this.selectedItemList[key];
        });
    }
    // 恢复选择状态
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData21 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");

                $('#tabData21 tbody tr:eq(' + index + ')').addClass("row__selected");
                // 设置删除按钮失效
                $(this).children('td').eq(2).children('span').eq(0).attr("onclick", "");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData21 tbody").find("tr").length || n === 0) {
            $("#CheckAll").prop("checked", false);
        } else {
            $("#CheckAll").prop("checked", true);
        }
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 214;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop - 50) / 25);
        let _dh = _rc * 25;
        let _rowH = this.rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD21").css({"max-height": _dh, height: _dh});
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_02").val());           // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        return JSON.stringify(item);
    }
    // 取得引入的调达表明细分页信息
    FetchForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/trade/shipping_order/lines/fetchForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_02 i").addClass("fa-spin");
                $("#loading__indicator_02").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_02 i").removeClass("fa-spin");
            $("#loading__indicator_02").hide();
        });
    }
    BuildDataTable(result) {
        $('#tabData31 tbody').empty();

        if (result.Success === false) {
            this.rows = 0;
            this.AutoAdjustTableHeightForLines();
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_02").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_02").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_02").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_02").data("swPagination").setPage(1);
        }
        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            this.rows = 0;
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            if (parseInt(result[i].rowFlag) === 0) {
                content_01 += '<tr _mash_id="' + result[i].linesId + '">';
                content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                content_01 += '<td style="text-align:center;" class="edited-cell">' + formatNullData(result[i].cartonNo) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].destination) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].styleNo) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].productName) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].colourNumber) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].colourName) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].sizeName) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].inBox) + '</td>';
                content_01 += '<td>' + result[i].inCase + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].shippingMarkNo) + '</td>';
                content_01 += '<td class="edited-cell">' + formatNullData(result[i].description) + '</td>';
                content_01 += '</tr>';
            }
            if (parseInt(result[i].rowFlag) === 1) {
                content_01 += '<tr style="background-color:#ffe4b5; color:#000;">';
                content_01 += '<td colspan="8" style="text-align:center;">小计</td>';
                content_01 += '<td>' + formatNullData(result[i].inBox) + '</td>';
                content_01 += '<td colspan="3"></td>';
                content_01 += '</tr>';
            }

            $('#tabData31 tbody').append(content_01);
            content_01 = '';
        }
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        $('#tabData31 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), _cellid, _cellname, 0);
        });

        setOneTableRowColor("tabData31");
    }
    GetLinesData() {
        let _result = {};
        let insertList = [];
        let updateList = [];
        //得到修改过数据
        $('#tabData31 tbody').find("tr").each(function () {
            let $tr1 = $(this);
            if ($tr1.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $tr1.attr("_mash_id");
                item['cartonNo'] = $.trim($tr1.find('td').eq(1).text());
                item['styleNo'] = $.trim($tr1.find('td').eq(3).text());
                item['productName'] = $.trim($tr1.find('td').eq(4).text());
                item['colourNumber'] = $.trim($tr1.find('td').eq(5).text());
                item['colourName'] = $.trim($tr1.find('td').eq(6).text());
                item['sizeName'] = $.trim($tr1.find('td').eq(7).text());
                item['inBox'] = $.trim($tr1.find('td').eq(8).text());
                item['inCase'] = $.trim($tr1.find('td').eq(9).text());
                item['shippingMarkNo'] = $.trim($tr1.find('td').eq(10).text()) === "" ? null : $.trim($tr1.find('td').eq(10).text());
                item['description'] = $.trim($tr1.find('td').eq(11).text()) === "" ? null : $.trim($tr1.find('td').eq(11).text());
                item['createdBy'] = $("#UserId").val();
                item['updatedBy'] = $("#UserId").val();
                if (parseInt($tr1.attr("_mash_id")) === 0) {
                    insertList.push(item);
                } else {
                    updateList.push(item);
                }
            }
        });
        _result["insertList"] = insertList;
        _result["updateList"] = updateList;
        _result['HeaderId'] = parseInt($("#HeaderId").val());
        _result['Limit'] = parseInt($("#page-size_02").val());
        _result['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));

        return JSON.stringify(_result);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.SaveLines("/trade/shipping_order/lines/save.html", function (data, _this) {
            if (data.Success === true) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("保存成功。");
            }
        });
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = parseInt($.trim($("#UserId").val()));
        params['Limit'] = parseInt($("#page-size_02").val());
        params['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        params['OrderBy'] = this.orderby;
        params['LinesData'] = "单据号：" + $("#BillNo").val() +
                "　箱号：" + $self.parent().parent().find("td").eq(1).text() +
                "　款号：" + $self.parent().parent().find("td").eq(3).text() +
                "　颜色：" + $self.parent().parent().find("td").eq(5).text() +
                "　尺码：" + $self.parent().parent().find("td").eq(7).text();

        super.DeleteLines(params, "/trade/shipping_order/lines/delete.html", function (data, _this) {
            if (data.Success === true) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("删除成功。");
            }
        });
    }
    BatchDeleteLines() {
        if ($('#tabData31 tbody').find("tr.row__selected").length === 0) {
            ShowErrorMessagePanel("请选择批量删除的记录。");
            return false;
        }
        super.BatchDeleteLines('/trade/shipping_order/lines/batchdelete.html', function (data, $self) {
            // 刷新本次发货生产情况
            //_InstancePageLinesMo.BuildDataTable(data.LinesMoList);
            // 刷新合同明细
            $self.BuildDataTable(data.LinesList);

            ShowSuccessMessagePanel("删除成功。");
            $("#CheckAll").prop("checked", false);
        });
    }
    InsertNewRow() {
        let $newLine_01 = $('<tr class="newLine" _mash_id="0" style=" border-top:1px solid #c6c3bd;">' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.RemoveNewRow($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td>' + $("#StyleNo").val() + '</td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell">' + $("#InCase").val() + '</td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');

        $('#tabData31 tbody').prepend($newLine_01);   // 加在后面

        let id = "_cell__field";
        let name = "__cell__field";
        $newLine_01.find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                //case 5:
                //    OnCellPopupEditEvent($(this), id, name, ($input) => {
                //        _this.DoChoiceColour($input);
                //    });
                //    OnCellPopupEditEvent($(this), id, name, this.DoChoiceColour);
                //    break;
                default:
                    OnCellClickEvent($(this), id, name, 0);
                    break;
            }
        });

        setOneTableRowColor("tabData31");
        this.rows = this.rows + 1;
    }
    RemoveNewRow($self) {
        showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            setOneTableRowColor("tabData31");

            this._rows = this._rows - 1;
            // 设置明细部分高度
            this.AutoAdjustTableHeightForLines();
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function () {}, function () {});
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 214;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        //$(document.body).append('<div id="test" style="background:red;width:100%;position:absolute; top:' + _tabTop + 'px;display:block;height:5px;z-index:10000" />');
        let _rc = Math.floor((h - _tabTop - 50) / 25);
        let _dh = _rc * 25;
        let _rowH = this.rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD31").css({"max-height": _dh, height: _dh});
    }
}

let _InstancePageHeader = null;
let _InstancePageLinesDo = null;
let _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let shipping_order_list_result = $.cookie("shipping_order_list_result") === undefined ? "" : $.cookie("shipping_order_list_result");
    let _pageListData = [];
    if (shipping_order_list_result !== "") {
        _pageListData = shipping_order_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/trade/shipping_order/list.html",
            "/trade/shipping_order/header/fetchByKey.html",
            "/trade/shipping_order/header/save.html",
            "/trade/shipping_order/header/export.html",
            "/trade/shipping_order/print.html");

    _InstancePageLinesDo = new MyPageLinesDo();
    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    // 设置分页控制 （操作区域）
    $("#wrapper__navbar_01").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_01").attr("_msh_page", page);
            _InstancePageLinesDo.FetchForPage(page);
        }
    });
    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", page);
            _InstancePageLines.FetchForPage(page);
        }
    });

    window.laydate.render({
        elem: '#DateOfSigning',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#DateOfArrival',
        theme: '#393D49',
        trigger: 'click'
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
    if (_InstancePageLinesDo !== null)
        _InstancePageLinesDo.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _DoBillNo: "required",
            _GarmentFactoryName: "required",
            _InCase: "required"
        },
        messages: {
            _BillNo: "请填写发货单号。",
            _DoBillNo: "请选择发货发令单号。",
            _GarmentFactoryName: "请填写加工厂。",
            _InCase: "请填写箱装。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 验证输入
function CheckGridInput() {
    $('#tabData31 tbody').find("tr").each(function (index) {
        let $tr1 = $(this);
        let _cartonNo = $.trim($tr1.find('td').eq(1).text()) === '' ? 0 : $.trim($tr1.find('td').eq(1).text()); // 
        let _productName = $.trim($tr1.find('td').eq(4).text());
        let _colourNumber = $.trim($tr1.find('td').eq(5).text());
        let _colourName = $.trim($tr1.find('td').eq(6).text());
        let _sizeName = $.trim($tr1.find('td').eq(7).text());
        let _inBox = $.trim($tr1.find('td').eq(8).text()) === '' ? 0 : $.trim($tr1.find('td').eq(8).text()); // 
        if (_cartonNo !== 0) {
            if (!isNumber(_cartonNo)) {
                GridCheckErrHandle($tr1, 1, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 1);
            }
        } else {
            GridCheckErrHandle($tr1, 1, '请输入箱号。');
        }
        if (_inBox !== 0) {
            if (!isNumber(_inBox)) {
                GridCheckErrHandle($tr1, 8, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 8);
            }
        } else {
            GridCheckErrHandle($tr1, 8, '请输入箱内数量。');
        }
        if (_productName === "") {
            GridCheckErrHandle($tr1, 4, '请输入品名。');
        } else {
            GridCheckSuccessHandle($tr1, 4);
        }
        if (_colourNumber === "") {
            GridCheckErrHandle($tr1, 5, '请输入色号。');
        } else {
            GridCheckSuccessHandle($tr1, 5);
        }
        if (_colourName === "") {
            GridCheckErrHandle($tr1, 6, '请输入颜色。');
        } else {
            GridCheckSuccessHandle($tr1, 6);
        }
        if (_sizeName === "") {
            GridCheckErrHandle($tr1, 7, '请输入尺码。');
        } else {
            GridCheckSuccessHandle($tr1, 7);
        }
    });
    if ($('#tabData31 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}